<template>
  <view class="page-container" :class="themeClass">
    <!-- 自定义导航栏 -->
    <CustomNavBar 
      title="搜索日记" 
      :show-back="true"
    />
    
    <!-- 页面内容 -->
    <view class="page-content">
      <!-- 搜索框 -->
      <view class="search-section">
        <view class="search-wrapper">
          <text class="search-icon">🔍</text>
          <input
            v-model="searchKeyword"
            placeholder="搜索日记内容、标题..."
            @input="handleInput"
            @confirm="handleSearch"
            class="search-input"
            focus
          />
          <view class="search-clear" v-if="searchKeyword" @click="clearSearch">
            <text class="clear-icon">×</text>
          </view>
        </view>
      </view>
      
      <!-- 搜索内容 -->
      <view class="search-content">
        <!-- 搜索结果 -->
        <view class="search-results" v-if="searchResults.length > 0">
          <view class="result-header">
            <text class="result-title">搜索结果</text>
            <text class="result-count">共 {{ searchResults.length }} 条</text>
          </view>
          
          <view class="results-list">
            <view 
              class="result-item"
              v-for="diary in searchResults"
              :key="diary.id"
              @click="goToDiaryDetail(diary.id)"
            >
              <view class="result-header-row">
                <text class="result-diary-title">{{ diary.title }}</text>
                <text class="result-date">{{ formatDate(diary.diaryDate) }}</text>
              </view>
              <text class="result-content">{{ diary.content }}</text>
              <view class="result-tags" v-if="diary.tags && diary.tags.length > 0">
                <view class="result-tag" v-for="tag in diary.tags.slice(0, 3)" :key="tag.id">
                  <text class="tag-text">{{ tag.name }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 搜索历史 -->
        <view class="search-history" v-if="!searchKeyword && searchHistory.length > 0">
          <view class="history-header">
            <text class="history-title">搜索历史</text>
            <text class="history-clear" @click="clearHistory">清空</text>
          </view>
          
          <view class="history-list">
            <view 
              class="history-item"
              v-for="(keyword, index) in searchHistory"
              :key="index"
              @click="searchByHistory(keyword)"
            >
              <text class="history-icon">🕐</text>
              <text class="history-text">{{ keyword }}</text>
              <text class="history-remove" @click.stop="removeHistory(index)">×</text>
            </view>
          </view>
        </view>
        
        <!-- 热门搜索 -->
        <view class="hot-search" v-if="!searchKeyword && hotKeywords.length > 0">
          <view class="hot-header">
            <text class="hot-title">热门搜索</text>
          </view>
          
          <view class="hot-list">
            <view 
              class="hot-item"
              v-for="keyword in hotKeywords"
              :key="keyword"
              @click="searchByKeyword(keyword)"
            >
              <text class="hot-text">{{ keyword }}</text>
            </view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view class="empty-state" v-if="showEmptyState">
          <text class="empty-icon">🔍</text>
          <text class="empty-text">{{ emptyText }}</text>
        </view>
        
        <!-- 搜索建议 -->
        <view class="search-tips" v-if="!searchKeyword">
          <view class="tips-header">
            <text class="tips-title">搜索小贴士</text>
          </view>
          <view class="tips-list">
            <view class="tip-item">
              <text class="tip-icon">💡</text>
              <text class="tip-text">输入关键词搜索日记标题和内容</text>
            </view>
            <view class="tip-item">
              <text class="tip-icon">🏷️</text>
              <text class="tip-text">使用标签名搜索相关日记</text>
            </view>
            <view class="tip-item">
              <text class="tip-icon">📅</text>
              <text class="tip-text">搜索特定日期的日记</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { useUserStore } from '@/store/user'
import { searchDiariesAPI } from '@/api/diary'
import { formatDate, extractResponseData } from '@/utils/index'
import CustomNavBar from '@/components/CustomNavBar.vue'

export default {
  name: 'SearchPage',
  components: {
    CustomNavBar
  },
  setup() {
    const userStore = useUserStore()
    
    return {
      userStore,
      formatDate
    }
  },
  data() {
    return {
      searchKeyword: '',
      searchResults: [],
      searchHistory: [],
      hotKeywords: ['快乐', '工作', '旅行', '美食', '电影', '书籍'],
      loading: false,
      searchTimer: null
    }
  },
  computed: {
    themeClass() {
      return this.userStore.themeMode === 'dark' ? 'theme-dark' : 'theme-light'
    },
    
    showEmptyState() {
      return this.searchKeyword && this.searchResults.length === 0 && !this.loading
    },
    
    emptyText() {
      return '未找到相关日记'
    }
  },
  onLoad() {
    this.loadSearchHistory()
  },
  methods: {
    // 加载搜索历史
    loadSearchHistory() {
      try {
        const history = uni.getStorageSync('searchHistory') || []
        this.searchHistory = history.slice(0, 10) // 最多保留10条
      } catch (error) {
        console.error('加载搜索历史失败:', error)
      }
    },
    
    // 保存搜索历史
    saveSearchHistory(keyword) {
      if (!keyword || keyword.trim() === '') return
      
      try {
        let history = uni.getStorageSync('searchHistory') || []
        
        // 移除重复项
        history = history.filter(item => item !== keyword)
        
        // 添加到开头
        history.unshift(keyword)
        
        // 限制数量
        history = history.slice(0, 10)
        
        uni.setStorageSync('searchHistory', history)
        this.searchHistory = history
      } catch (error) {
        console.error('保存搜索历史失败:', error)
      }
    },
    
    // 输入处理
    handleInput(e) {
      const value = e.detail.value
      this.searchKeyword = value
      
      // 清除之前的定时器
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      
      // 防抖搜索
      if (value.trim()) {
        this.searchTimer = setTimeout(() => {
          this.performSearch(value.trim())
        }, 500)
      } else {
        this.searchResults = []
      }
    },
    
    // 搜索确认
    handleSearch() {
      const keyword = this.searchKeyword.trim()
      if (keyword) {
        this.performSearch(keyword)
      }
    },
    
    // 执行搜索
    async performSearch(keyword) {
      if (!keyword) return
      
      this.loading = true
      
      try {
        const res = await searchDiariesAPI({
          keyword,
          page: 1,
          limit: 20
        })
        
        const data = extractResponseData(res)
        this.searchResults = data.diaries || []
        this.saveSearchHistory(keyword)
        
      } catch (error) {
        console.error('搜索失败:', error)
        uni.showToast({
          title: '搜索失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 按历史记录搜索
    searchByHistory(keyword) {
      this.searchKeyword = keyword
      this.performSearch(keyword)
    },
    
    // 按关键词搜索
    searchByKeyword(keyword) {
      this.searchKeyword = keyword
      this.performSearch(keyword)
    },
    
    // 清空搜索
    clearSearch() {
      this.searchKeyword = ''
      this.searchResults = []
    },
    
    // 清空历史
    clearHistory() {
      uni.showModal({
        title: '确认清空',
        content: '确定要清空搜索历史吗？',
        success: (res) => {
          if (res.confirm) {
            uni.removeStorageSync('searchHistory')
            this.searchHistory = []
          }
        }
      })
    },
    
    // 删除单条历史
    removeHistory(index) {
      this.searchHistory.splice(index, 1)
      uni.setStorageSync('searchHistory', this.searchHistory)
    },
    
    // 跳转到日记详情
    goToDiaryDetail(id) {
      uni.navigateTo({
        url: `/pages/diary/detail?id=${id}`
      })
    }
  }
}
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}



.page-content {
  padding: 40rpx;
  padding-top: calc(var(--status-bar-height, 44rpx) + 88rpx + 40rpx);
  min-height: calc(100vh - calc(var(--status-bar-height, 44rpx) + 88rpx));
}

.search-section {
  margin-bottom: 40rpx;
}

.search-wrapper {
  display: flex;
  align-items: center;
  background-color: #ffffff;
  border-radius: 40rpx;
  padding: 24rpx 32rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.search-icon {
  font-size: 28rpx;
  color: #999999;
  margin-right: 16rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333333;
  border: none;
  outline: none;
}

.search-clear {
  padding: 8rpx;
  margin-left: 16rpx;
}

.clear-icon {
  font-size: 32rpx;
  color: #cccccc;
}

.search-content {
  display: flex;
  flex-direction: column;
  gap: 40rpx;
}

.search-results {
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;
}

.result-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.result-count {
  font-size: 26rpx;
  color: #666666;
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 32rpx;
}

.result-item {
  padding: 24rpx;
  border-radius: 16rpx;
  background-color: #f8f8f8;
  transition: background-color 0.2s;
}

.result-item:active {
  background-color: #f0f0f0;
}

.result-header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.result-diary-title {
  font-size: 28rpx;
  font-weight: 500;
  color: #333333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.result-date {
  font-size: 24rpx;
  color: #999999;
}

.result-content {
  font-size: 26rpx;
  color: #666666;
  line-height: 1.6;
  margin-bottom: 16rpx;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.result-tags {
  display: flex;
  gap: 12rpx;
  flex-wrap: wrap;
}

.result-tag {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  font-size: 22rpx;
}

.tag-text {
  font-size: 22rpx;
}

.search-history {
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;
}

.history-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.history-clear {
  font-size: 26rpx;
  color: #1890ff;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.history-item {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.history-item:last-child {
  border-bottom: none;
}

.history-icon {
  font-size: 24rpx;
  color: #999999;
  margin-right: 16rpx;
}

.history-text {
  flex: 1;
  font-size: 28rpx;
  color: #333333;
}

.history-remove {
  font-size: 32rpx;
  color: #cccccc;
  padding: 8rpx;
}

.hot-search {
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.hot-header {
  margin-bottom: 32rpx;
}

.hot-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.hot-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.hot-item {
  background-color: #f0f0f0;
  color: #666666;
  padding: 16rpx 24rpx;
  border-radius: 24rpx;
  font-size: 26rpx;
  transition: background-color 0.2s;
}

.hot-item:active {
  background-color: #e0e0e0;
}

.hot-text {
  font-size: 26rpx;
}

.empty-state {
  text-align: center;
  padding: 120rpx 40rpx;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 32rpx;
  display: block;
}

.empty-text {
  font-size: 32rpx;
  color: #666666;
}

.search-tips {
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.tips-header {
  margin-bottom: 32rpx;
}

.tips-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.tips-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.tip-icon {
  font-size: 32rpx;
}

.tip-text {
  font-size: 28rpx;
  color: #666666;
  line-height: 1.4;
}

/* 主题适配 */
.theme-light.page-container {
  background-color: #f5f5f5 !important;
}

.theme-dark.page-container {
  background-color: #1e1e1e !important;
}

.theme-dark .search-wrapper,
.theme-dark .search-results,
.theme-dark .search-history,
.theme-dark .hot-search,
.theme-dark .search-tips {
  background-color: #252526 !important;
}

.theme-dark .search-input {
  background-color: #3c3c3c !important;
  color: #e8e8e8 !important;
}

.theme-dark .search-input::placeholder {
  color: #b3b3b3 !important;
}

.theme-dark .result-title,
.theme-dark .history-title,
.theme-dark .hot-title,
.theme-dark .tips-title,
.theme-dark .result-diary-title,
.theme-dark .history-text {
  color: #e8e8e8 !important;
}

.theme-dark .result-count,
.theme-dark .result-content,
.theme-dark .tip-text,
.theme-dark .empty-text {
  color: #b3b3b3 !important;
}

.theme-dark .result-date,
.theme-dark .history-icon,
.theme-dark .history-remove {
  color: #8c8c8c !important;
}

.theme-dark .result-item {
  background-color: #2d2d30 !important;
}

.theme-dark .result-item:active {
  background-color: #404040 !important;
}

.theme-dark .history-item {
  border-bottom-color: #404040 !important;
}

.theme-dark .hot-item {
  background-color: #404040 !important;
  color: #b3b3b3 !important;
}

.theme-dark .hot-item:active {
  background-color: #4a4a4a !important;
}

.theme-dark .result-tag {
  background-color: #1e3a8a !important;
  color: #60a5fa !important;
}

.theme-dark .clear-icon {
  color: #b3b3b3 !important;
}

.theme-dark .search-clear {
  background-color: #404040 !important;
}

.theme-dark .history-clear {
  color: #60a5fa !important;
}
</style> 